﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Text;
using System.Media;
using Game.Klassen;

namespace Game.Frames
{
    public partial class controlLevelAuswahl : UserControl
    {
        #region Initialisieren

        //Eigenschaften
        private int                     mouseLastPosX   = 0;
        private PrivateFontCollection   customFont      = new PrivateFontCollection();
        private Main                    fenster;
        List<BackGroundObject>          bgObjects;

        //Grafik zum Zeichnen
        Graphics    g;
        Image       bm;


        //Konstruktor
        public controlLevelAuswahl(Main fenster)
        {
            InitializeComponent();

            //Hauptfenster setzen / Cursor icon
            this.fenster    = fenster;

            //Image und Graphics init
            bm  = (Image)new Bitmap(pbBG.Width, pbBG.Height);
            g   = Graphics.FromImage(bm);

            //Eigene Font laden
            if (File.Exists("./Files/GhostOfMars.ttf"))
            {
                customFont.AddFontFile("./Files/GhostOfMars.ttf");
                FontFamily fontFam = customFont.Families[0];

                Font buttonFont = new Font(fontFam, 24, FontStyle.Bold);
                Font listFont = new Font(fontFam, 18, FontStyle.Regular);
                Font listHFont = new Font(fontFam, 18, FontStyle.Bold);

                //Kompenenten Font zuweisen
                btLoadFile.Font = buttonFont;
                btPlay.Font     = buttonFont;
                lblB.Font       = buttonFont;
                lblCount.Font   = buttonFont;
                lblH.Font       = buttonFont;
                lblHeight.Font  = buttonFont;
                lblWidth.Font   = buttonFont;
                lblSpielerzahl.Font = buttonFont;

                dataGrid.RowsDefaultCellStyle.Font          = listFont;
                dataGrid.ColumnHeadersDefaultCellStyle.Font = listHFont;
            }

            //Maps Ordner lesen und in dataGridView einfügen
            if (Directory.Exists("./Files/Maps"))
            {
                string[] files = Directory.GetFiles("./Files/Maps");

                foreach (string file in files)
                    if (file.EndsWith(".map"))
                    {
                        string configRow = File.ReadAllLines(file)[0].Split(';')[0];
                        dataGrid.Rows.Add(configRow, file.Replace(@"\", @"/"));
                    }
            }


            //bgObjects init
            bgObjects = new List<BackGroundObject>();
            for (int x = 0; x < this.Width; x++)
                if (x % 100 == 0)
                {
                    bgObjects.Add(new Bubble(new Point(x, Session.rand.Next(0, 800)), new Size(40, 40), true, "left"));
                    bgObjects.Add(new Bubble(new Point(x, Session.rand.Next(100, 800)), new Size(20, 20), true, "right"));
                }
        }

        #endregion

        #region Events
        //Doppelklick level starten
        private void dataGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            btPlay.PerformClick();
        }

        //Button Hover
        private void btHover_MouseEnter (object sender, EventArgs e)
        {
            ((Button)sender).Image = Game.Properties.Resources.button_hover;
        }

        private void btHover_MouseLeave (object sender, EventArgs e)
        {
            ((Button)sender).Image = Game.Properties.Resources.button;
        }

        private void btBack_MouseEnter  (object sender, EventArgs e)
        {
            ((Button)sender).Image = Game.Properties.Resources.back_hover;
        }

        private void btBack_MouseLeave  (object sender, EventArgs e)
        {
            ((Button)sender).Image = Game.Properties.Resources.back_normal;
        }


        //Auswahl der Karte wurde geändert
        private void dataGrid_SelectionChanged(object sender, EventArgs e)
        {
            //SpeilerZahl und Dateipfad auf dataGrid holen
            string playerCount  = dataGrid.SelectedRows[0].Cells[0].Value.ToString();
            string file         = dataGrid.SelectedRows[0].Cells[1].Value.ToString();

            //Konfiguration aus Datei lesen
            string[] cfgRow     = File.ReadAllLines(file)[0].Split(';');
            string[] mapLines   = File.ReadAllLines(file);

            //Kartenmaße lesen
            string height   = cfgRow[2];
            string width    = cfgRow[1];

            int iHeight = int.Parse(height);
            int iWidth  = int.Parse(width);

            //Labels Updaten
            lblWidth.Text   = width;
            lblHeight.Text  = height;
            lblCount.Text   = playerCount;

            //Größe pro Kästchen für Vorschau ermitteln
            int dotSize = 300 / (iHeight > iWidth ? iHeight : iWidth);

            //Kartenvorschau
            Image img           = (Image)new Bitmap(iWidth * dotSize, iHeight * dotSize);
            Graphics g          = Graphics.FromImage(img);

            SolidBrush bgBrush  = new SolidBrush(Color.FromArgb(0, 170, 220));
            SolidBrush fgBrush  = new SolidBrush(Color.FromArgb(0, 100, 150));

            //Hintergrund und "Sonnenstrahlen"
            g.FillRectangle (bgBrush, 0, 0, iWidth * dotSize, iHeight * dotSize);
            g.DrawImage     (Game.Properties.Resources.shine, 0, 0, iWidth * dotSize, iHeight * dotSize);

            //Map Tiles malen
            for (int x = 2; x < (2 + iHeight); x++)
            {
                string[] line = mapLines[x].Split(';');
                for (int y = 0; y < line.Length; y++)
                {
                    if (!line[y].StartsWith("0"))
                        g.FillRectangle(fgBrush, y * dotSize, (x - 2) * dotSize, dotSize, dotSize);
                }
            }

            //Picturebox Updaten
            pbPreview.Image = img;
        }

        //Beenden
        private void LevelAuswahl_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        //Mausbewegung SPeichern
        private void controlLevelAuswahl_MouseMove(object sender, MouseEventArgs e)
        {
            mouseLastPosX = ((Control)sender).Location.X + e.X;
        }

        //Hauptmenü wieder anzeigen
        private void btBack_Click       (object sender, EventArgs e)
        {
            fenster.showMenu();
        }

        //Ausgewählte Karte der Liste starten
        private void btPlay_Click       (object sender, EventArgs e)
        {
            string file = dataGrid.SelectedRows[0].Cells[1].Value.ToString();
            fenster.showGame(file);
        }

        //Karte aus Datei laden über OpenFileDialog
        private void btLoadFile_Click   (object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "map files (*.map)|*.map|All files (*.*)|*.*";
            dialog.Multiselect = false;

            if (dialog.ShowDialog() == DialogResult.OK)
                fenster.showGame(dialog.FileNames[0]);
        }
        #endregion

        //Rendering Hintergrund
        private void mainloop_Tick(object sender, EventArgs e)
        {
            //Hintergrundfarbe
            g.Clear(Color.FromArgb(0, 150, 220));

            //Bild verschieben und Zeichnen
            g.DrawImage(Game.Properties.Resources.bgLevelSelection, -1*mouseLastPosX / 80, 0, 1024, 770);

            //Hintergrundobjekte malen
            foreach (BackGroundObject obj in bgObjects)
            {
                obj.Update();
                g.DrawImage(obj.getImage(), obj.position.X + obj.offset.X, obj.position.Y + obj.offset.Y, obj.size.Width, obj.size.Height);
            }

            //Labels Mitbewegen
            lblSpielerzahl.Location = new Point(737 - mouseLastPosX / 80, lblSpielerzahl.Location.Y);
            lblH.Location           = new Point(737 - mouseLastPosX / 80, lblH.Location.Y);
            lblB.Location           = new Point(737 - mouseLastPosX / 80, lblB.Location.Y);

            lblWidth.Location       = new Point(881 - mouseLastPosX / 80, lblWidth.Location.Y);
            lblHeight.Location      = new Point(881 - mouseLastPosX / 80, lblHeight.Location.Y);
            lblCount.Location       = new Point(881 - mouseLastPosX / 80, lblCount.Location.Y);


            btBack.Location     = new Point(32 + mouseLastPosX / 150, 702);
            dataGrid.Location   = new Point(12 + mouseLastPosX / 150, 12);
            pbPreview.Location  = new Point(696 + mouseLastPosX / 150, 12);

            btLoadFile.Location = new Point(696 + mouseLastPosX / 150, 619);
            btPlay.Location     = new Point(696 + mouseLastPosX / 150, 677);

            //Picturebox update
            pbBG.Image = bm;
        }

        
    }
}
